package src.com.neusoft.nep.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import src.com.neusoft.nep.common.AlertUtils;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.common.SwitchScene;
import src.com.neusoft.nep.entity.ReceivedData;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class NepgTaskManageViewController {
    @FXML
    private ImageView imageView;
    @FXML
    private AnchorPane anchorPane;
    @FXML
    private Button btn_taskManageBack, btn_deleteTaskData;

    @FXML
    private TableView<ReceivedData> tableView;
    @FXML
    private TableColumn<ReceivedData,String> colLevel, colProvince, colCity, colLocation, colTime;
    @FXML
    private TableColumn<ReceivedData,Void> colDetect;

    private ObservableList<ReceivedData> firstTableList = FXCollections.observableArrayList();
    private ObservableList<ReceivedData> secondTableList = FXCollections.observableArrayList();
    private ObservableList<ReceivedData> thirdTableList = FXCollections.observableArrayList();
    Map<String, ReceivedData> receivedDataMap = new HashMap<>();

    public void backToLogin() throws IOException {
        SwitchScene.switchScene(btn_taskManageBack, "../view/NepgLoginView.fxml");
    }

    @FXML
    public void initialize() {

        Image image = new Image("/src/com/neusoft/nep/image/Nepg02.png");
        imageView.setImage(image);
        imageView.fitHeightProperty().bind(anchorPane.heightProperty());
        imageView.fitWidthProperty().bind(anchorPane.widthProperty());
        imageView.setPreserveRatio(false);
        imageView.setSmooth(true);

        colLevel.setCellValueFactory(new PropertyValueFactory<>("level"));
        colProvince.setCellValueFactory(new PropertyValueFactory<>("province"));
        colCity.setCellValueFactory(new PropertyValueFactory<>("city"));
        colLocation.setCellValueFactory(new PropertyValueFactory<>("location"));
        colTime.setCellValueFactory(new PropertyValueFactory<>("time"));
//        tableList.add(new ReceivedData("一", "广东省", "广州", "华南农业大学", "1", "1", "1", "1", "11"));
//        tableList.add(new ReceivedData("二", "江西省", "新余", "新余一中", "2", "2", "2", "2", "22"));

        //读取文件
        // 先清空所有列表（避免重复添加）
        firstTableList.clear();
        secondTableList.clear();
        thirdTableList.clear();

        receivedDataMap = FileUtils.readMapObject("gridReceivedData.txt");
        for (ReceivedData rd : receivedDataMap.values()) {
            if (rd.getGridInspector().equals("11")){
                firstTableList.add(rd);
            }else if (rd.getGridInspector().equals("22")) {
                secondTableList.add(rd);
            }else if (rd.getGridInspector().equals("33")) {
                thirdTableList.add(rd);
            }
        }

        // 从单例获取登录的code
        String loginCode = NepgLoginViewController.getInstance().getLoggedInCode();
        if (loginCode != null) {
            System.out.println("获取到的登录code: " + loginCode);
            // 根据code设置表格数据
            switch (loginCode) {
                case "11":
                    tableView.setItems(firstTableList);
                    break;
                case "22":
                    tableView.setItems(secondTableList);
                    break;
                case "33":
                    tableView.setItems(thirdTableList);
                    break;
                default:
                    tableView.setItems(firstTableList);
                    System.out.println("未知的code: " + loginCode);
            }
        } else {
            System.out.println("未获取到登录code，可能未登录");
        }



        //动态添加按钮列
        colDetect.setCellFactory(cols->new TableCell<>(){
            private Button btn = new Button("去检测");
            {
                btn.setOnAction(e->{
                    ReceivedData rd = getTableView().getItems().get(getIndex());
                    Stage stage = new Stage();
                    FXMLLoader fxmlLoader = new FXMLLoader();
                    URL url = getClass().getResource("../view/NepgTaskInformationView.fxml");
                    fxmlLoader.setLocation(url);
                    Parent root = null;
                    try {
                        root = fxmlLoader.load();
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                    NepgTaskInformationViewController controller = fxmlLoader.getController();
                    controller.setReceivedData(rd);
                    controller.setCurrentStage(stage);

                    Scene scene = new Scene(root);
                    stage.setScene(scene);
                    stage.showAndWait();
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty?null:btn);
            }
        });
    }

    public void deleteTaskData() {
        ReceivedData deleteData = (ReceivedData)tableView.getSelectionModel().getSelectedItem();
        firstTableList.remove(deleteData);
        secondTableList.remove(deleteData);
        thirdTableList.remove(deleteData);
        receivedDataMap.remove(deleteData.getLocation());
        FileUtils.writeMapObject("gridReceivedData.txt", receivedDataMap);
        AlertUtils.showDialog("", "删除成功");
    }

}
